package smartt.styy.auth.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import smartt.styy.auth.config.UserConfiguration;
import smartt.styy.auth.model.jwt.IJWTInfo;
import smartt.styy.auth.model.utils.JwtTokenUtil;
import smartt.styy.auth.util.DESEncrypt;
import smartt.styy.auth.util.HttpHelper;
import smartt.styy.auth.util.JsonUtil;
import smartt.styy.common.constant.RestCodeConstants;
import smartt.styy.common.context.BaseContextHandler;
import smartt.styy.common.exception.auth.UserTokenException;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shangtengfei
 */
@Slf4j
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(UserAuthRestInterceptor.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserConfiguration userConfiguration;

    @Value("${3des.key}")
	private String desKey;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>> preHandle方法start ...");
    	
    	String token = request.getHeader(userConfiguration.getUserTokenHeader());
    	IJWTInfo infoFromToken =null;
    	try {
    		infoFromToken = jwtTokenUtil.getInfoFromToken(token);
		} catch (ExpiredJwtException e) {
			throw new UserTokenException("请求token过期，请稍后重试！");
		}
        long effectiveTime = infoFromToken.getEffectiveTime();
        //token过期
        if(effectiveTime <1){
        	log.error("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求token过期，请稍后重试！");
        	throw new UserTokenException("请求token过期，请稍后重试！");
        }
        String body = HttpHelper.getBodyString(request);
        String paramUserId = request.getParameter("userId");
        String userId =new String();
        Map<String, Object> bodyMap =new HashMap<String,Object>();
        if(!StringUtils.isEmpty(body)){
        	bodyMap = JsonUtil.asMapWithStringKey(body, Object.class);
        	log.info("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求body数据："+bodyMap);
        }
        if(bodyMap.get("userId") != null ){
        	String bodyUserId = bodyMap.get("userId").toString();
        	try {
        		userId = DESEncrypt.decryptMode(desKey,bodyUserId);
        	} catch (Exception e) {
        		log.error("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求body数据,userId传入错误，请核实！！！");
        		throw new UserTokenException("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求body数据,userId传入错误,错误信息message:"+
        				e.getMessage(),RestCodeConstants.TOKEN_ERROR_CODE);
        	}
        	if(!userId.equals(infoFromToken.getId())){
        		logger.error("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!");
            	throw new UserTokenException("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!",RestCodeConstants.TOKEN_ERROR_CODE);
        	}
        	
        }else if(paramUserId != null){
        	log.info("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求parameter-userId参数数据："+paramUserId);
        	
        	try {
        		userId = DESEncrypt.decryptMode(desKey,paramUserId);
        	} catch (Exception e) {
        		log.error("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>请求parameter-解密userId异常，错误message："+e.getMessage());
        		throw new UserTokenException("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数信息,错误信息message:"+
        				e.getMessage(),RestCodeConstants.TOKEN_ERROR_CODE);
        	}
        	
        	if(!userId.equals(infoFromToken.getId())){
        		logger.error("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!");
            	throw new UserTokenException("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!",RestCodeConstants.TOKEN_ERROR_CODE);
        	}
        	
        }else{
    		logger.error("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!");
        	throw new UserTokenException("[认证服务器][auth-server]用户请求认证服务异常，请检查请求参数和header-token信息!",RestCodeConstants.TOKEN_ERROR_CODE);
        }
        
        BaseContextHandler.setUsername(infoFromToken.getUniqueName());
        BaseContextHandler.setName(infoFromToken.getNickName());
        BaseContextHandler.setUserTypes(infoFromToken.getUserTypes());
        BaseContextHandler.setUserID(infoFromToken.getId());    
        log.info("[认证服务器][auth-server]<<<<<<UserAuthRestInterceptor拦截器>>>>>>验证通过。。。。successful!!!");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
